/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.edu.fpt.xml.hrm.controller.auth;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.Logger;
import org.apache.fop.apps.Driver;
import org.xml.sax.InputSource;
import vn.edu.fpt.xml.hrm.controller.AbstractController;

/**
 *
 * @author ANHNH8
 */
public class CombineFOWithXSL extends AbstractController {

    @Override
    protected String execute() {
        HttpServletRequest request = this.getRequest();
        HttpServletResponse response = this.getResponse();
        try{
            String path = getServletContext().getRealPath("/");
            //String path = "C:/XML/XMLProject/trunk/Source code/XML Netbeans/web";
            String xslPath = path + "WEB-INF/payrollFO.xsl";
            String xmlPath = path + "WEB-INF/payrollPDF.xml";

            String foPath = path + "payrollFO.fo";
            methodTrAX(xslPath, xmlPath, foPath);
            File file = new File(foPath);
            FileInputStream input = new FileInputStream(file);

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.setContentType("application/pdf");
            Driver driver = new Driver(new InputSource(input), out);
            Logger log = new ConsoleLogger(ConsoleLogger.LEVEL_WARN);
            driver.setRenderer(Driver.RENDER_PDF);
            driver.run();
            byte[] content = out.toByteArray();
            response.setContentLength(content.length);
            response.getOutputStream().write(content);
            response.getOutputStream().flush();



        } catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }
    private void methodTrAX (String xslPath, String xmlPath, String output){
        try{
            TransformerFactory tf = TransformerFactory.newInstance();
            StreamSource xsltFile = new StreamSource(xslPath);
            Transformer trans = tf.newTransformer(xsltFile);
            StreamSource xmlFile = new StreamSource(xmlPath);
            StreamResult htmlFile = new StreamResult(new FileOutputStream(output));
            trans.transform(xmlFile, htmlFile);

        } catch (TransformerConfigurationException ex){
            ex.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    }
